const express = require('express');
const db = require('./db');

let app = express();
app.use(express.static("./public"))
app.get("/list", (req, res) => {
    let pageNum = req.query.pageNum * 1 || 1
    let pageSize = req.query.pageSize * 1 || 10
    let startNum = (pageNum - 1) * pageSize
    let connection = db()
    connection.connect(err => {
        if (err) {
            return console.log("连接数据库失败", err);
        }
        connection.query("select * from user limit ?,?", [startNum, pageSize], (err, result) => {
            if (err) {
                return console.log("查询失败:", err);
            }
            console.log("查询成功", result);
            res.json({ list: result })
        })
        connection.end()
    })
})
app.get("/add", (req, res) => {
    let userName = req.query.userName
    let password = req.query.password

    let connection = db()
    connection.connect(err => {
        if (err) {
            return console.log("连接数据库失败:", err);
        }
        connection.query("insert into user(userName,password) values( ?, ?)", [userName, password], (err, result) => {
            if (err) {
                return console.log("添加失败:", err);
            }
            console.log("添加成功", result);
        })
        connection.end()
    })
    res.send("添加成功")
})
app.get("/del", (req, res) => {
    let id = req.query.id

    let connection = db()
    connection.connect(err => {
        if (err) {
            return console.log("连接数据库失败", err);
        }
        connection.query("delete from user where Id= ?", [id], (err, result) => {
            if (err) {
                return console.log("删除失败:", err);
            }
            console.log("删除成功");
            res.json({
                list:result
            })
        })
        
        connection.end()
    })
})
app.get("/change",(req,res)=>{
    let connection = db()
    let {userName,password,id} = req.query
    connection.connect(err=>{
        if (err) {
            return console.log("更改数据库错误：",err);
        }
        connection.query(`update user set userName=?,password=? where id=?`,[userName,password,id],(err,result)=>{
            if (err) {
                return console.log("更改数据库失败",err);
            }
            res.json({
                list:result
            })
            connection.end()
        })
    })
})
app.listen(8989, () => {
    console.log("8989服务启动");
})